package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private MinioClient minioClient;

	@Autowired
	private MinioProperties minioProperties;

	@Override
	public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

			//检查存储桶是否已经存在于 MinIO 服务器上
			//如果存在，则返回 true；否则返回 false
			boolean b = minioClient.bucketExists(BucketExistsArgs.builder()
					.bucket(minioProperties.getBucketName())
					.build());
			if (!b){
				//创建一个新的存储桶
				minioClient.makeBucket(MakeBucketArgs.builder()
						.bucket(minioProperties.getBucketName())
						.build());
				//设置存储桶的访问策略
				minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
						.bucket(minioProperties.getBucketName())
						.config(createBucketPolicyConfig(minioProperties.getBucketName()))
						.build());
			}
			// 对象名
			String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
			// 将流中的数据上传到对象.
			minioClient.putObject(PutObjectArgs.builder()
					.bucket(minioProperties.getBucketName())    //桶
							.object(filename)   //文件名
							.stream(file.getInputStream(), file.getSize(), -1)   //指定输入流
							.contentType(file.getContentType())
					.build());
			// String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + filename;
			return String.join("/",minioProperties.getEndpoint(),minioProperties.getBucketName(),filename);
	}

	private String createBucketPolicyConfig(String bucketName) {
		// Action：操作方式
		// Effect：动作
		// Principal：用户
		// Resource：arn:aws:s3:::桶下的/所有资源
		// 允许Allow——所有用户*——获取GetObject——桶%s下的/*所有资源
		return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
	}
}
